import React, { Component } from 'react';
import {
	StyleSheet,
	Text,
	View,
	Image,
	Platform,
	TouchableOpacity,
	TextInput,
	PixelRatio,
	Alert,
	Keyboard,
	DeviceEventEmitter,
	StatusBar,
	Animated,
	Dimensions,
	KeyboardAvoidingView,
} from "react-native";
import * as Keychain from 'react-native-keychain';
import TouchID from 'react-native-touch-id';

import { API, API_GENERATE } from '../../config/api'
import StorageHelper from '../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../config/storage';
import { style } from '../../theme/style';
import { GLOBAL } from '../../config/global';
import { ENVIRONMENT } from '../../config/env'
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { HxActionSheet } from '../../component/HxActionSheet';
import ToastUtil from '../../utils/toast';
import HTTP from '../../utils/http';
import Dictionary from '../../utils/dictionary';
import Permission from '../../utils/permission';

const appInfo = require('react-native-device-info');
const logoIcon = require('../../imgs/global/logo.png');
const showIcon = require('../../imgs/global/eye0.png');
const hideIcon = require('../../imgs/global/eye1.png');
const inputsCellShadow = require('../../imgs/auth/androidBg.png');
const inputClear = require('../../imgs/global/inputDelete.png');
const ScreenWidth = Dimensions.get('window').width;
const ScreenHeight = Dimensions.get('window').height;
const scale = GLOBAL.SCALE;

const envStatus = {
	'1': 'DEV',
	'2': 'TEST',
	'3': 'UAT',
	'4': 'PREP',
	'5': 'ZHDS',
	'6': 'PROD'
}
const envStatusProd = {
	'1': 'PROD',
	'2': 'ZHDS'
}

export class LoginPage extends Component {
	static navigationOptions = {
		header: null,
		gesturesEnabled: false //禁止侧滑返回事件
	}

	requesting;

	constructor(props) {
		super(props);
		this.state = {
			current_env_title: ENVIRONMENT[GLOBAL.CURR_ENV].hideLabel ? '' : "(" + ENVIRONMENT[GLOBAL.CURR_ENV].title + ")",
			accountClearOpacity: 0,
			passwordClearOpacity: 0,
			hidePassword: true,
			status: 'data',
			accountFocus: false,
			passwordFocus: false,
			isBind: false,
			gesture:false
		};
		this.loginInfo = {
			loginName: '',
			password: ''
		}
		this.isIOS = Platform.OS === 'ios';
		this.imageHeight = new Animated.Value(70 * scale);
		this.inputWrapTop = new Animated.Value(180 * scale);
		this.inputWrapHeight = new Animated.Value(387 * scale);
		this.inputMarginTop = new Animated.Value(36 * scale);
		this.textOpacity = new Animated.Value(1);
	}


	async componentWillMount () {
		this.keyboardWillShowSub = Keyboard.addListener(this.isIOS ? 'keyboardWillShow' : 'keyboardDidShow', this.keyboardWillShow);
		this.keyboardWillHideSub = Keyboard.addListener(this.isIOS ? 'keyboardWillHide' : 'keyboardDidHide', this.keyboardWillHide);
		DeviceEventEmitter.addListener('current_env', (env) => {
			this.setState({
				current_env_title: !ENVIRONMENT[env].hideLabel ? '' : "(" + ENVIRONMENT[env].title + ")",
			})
		})

		let account = await StorageHelper.get(STORAGE_CONSTANT.LOGIN_ACCOUNT_KEY);
		GLOBAL.BIND_GESTURE_PASSWORD = await StorageHelper.get(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD);
		if (account) {
			this.loginInfo.loginName = account;
			this.refs.accountInput && this.refs.accountInput.blur();
			this.setState({
				accountClearOpacity: 1
			});

			if (GLOBAL.SUPPORT_BIOMETRY_TYPE) {
				this.setState({
					isBind: GLOBAL.BIND_BIOMETRY_AUTH
				})
			} else {
				// ToastUtil.showWarning('当前手机不支持识别')
			}
			if(GLOBAL.BIND_GESTURE_PASSWORD) {
				this.setState({
					gesture: true
				})
			}
		}

		const appHotVersion = await StorageHelper.get(STORAGE_CONSTANT.APP_HOT_VERSION);
		this.setState({
			appHotVersion: appHotVersion
		})
	}
	async refreshData() {
		let account = await StorageHelper.get(STORAGE_CONSTANT.LOGIN_ACCOUNT_KEY);
		GLOBAL.BIND_GESTURE_PASSWORD = await StorageHelper.get(STORAGE_CONSTANT.BIND_GESTURE_PASSWORD);
		if (account&&GLOBAL.BIND_GESTURE_PASSWORD) {
			this.setState({
				gesture: true
			})
		}
		else{
			this.setState({
				gesture: false
			})
		}
	}

	async componentDidMount () {
		
		let { params } = this.props.navigation.state;
		if (params && params.autoLogin && params.username && params.password) {
			//开启指纹识别
			this.authenticate()
		}
		console.log(params)
	}

	componentWillUnmount () {
		this.keyboardWillShowSub.remove();
		this.keyboardWillHideSub.remove();
	}

	keyboardWillShow = (event) => {
		Animated.parallel([
			Animated.timing(this.imageHeight, {
				duration: 300,
				toValue: 40 * scale,
			}),
			Animated.spring(this.inputWrapTop, {
				duration: 300,
				toValue: 110 * scale,
			}),
			Animated.timing(this.inputWrapHeight, {
				duration: 300,
				toValue: 340 * scale,
			}),
			Animated.timing(this.inputMarginTop, {
				duration: 300,
				toValue: 24 * scale,
			}),
			Animated.timing(this.textOpacity, {
				duration: 300,
				toValue: 0,
			}),
		]).start()
	};

	keyboardWillHide = (event) => {
		Animated.parallel([
			Animated.timing(this.imageHeight, {
				duration: 300,
				toValue: 70 * scale,
			}),
			Animated.spring(this.inputWrapTop, {
				duration: 300,
				toValue: 180 * scale,
			}),
			Animated.timing(this.inputWrapHeight, {
				duration: 300,
				toValue: 387 * scale,
			}),
			Animated.timing(this.inputMarginTop, {
				duration: 300,
				toValue: 36 * scale,
			}),
			Animated.timing(this.textOpacity, {
				duration: 300,
				toValue: 1,
			}),
		]).start()
	};

	switchEnviromentSelect () {
		this.SwitchActionSheet.onShowCustomActionSheet();
	}

	async switchEnviroment (env) {
		if (!env) {
			return
		} else if (env == GLOBAL.CURR_ENV) {
			Alert.alert(`当前就是${ENVIRONMENT[env].title}环境~`);
		} else {
			await StorageHelper.set(STORAGE_CONSTANT.CURR_ENV, env);
			GLOBAL.CURR_ENV = env;
			this.setState({
				current_env_title: ENVIRONMENT[GLOBAL.CURR_ENV].hideLabel ? '' : "(" + ENVIRONMENT[GLOBAL.CURR_ENV].title + ")",
			})
		}
	}

	getAccount = info => {
		this.loginInfo.loginName = info;
		this.setState({
			accountClearOpacity: info.length > 0 ? 1 : 0
		})
	}
	getPassword = info => {
		this.loginInfo.password = info;
		this.setState({
			passwordClearOpacity: info.length > 0 ? 1 : 0
		})
	}

	clearAccount = () => {
		this.refs.accountInput.clear();
		this.loginInfo.loginName = '';
		this.setState({
			accountClearOpacity: 0
		})
	}

	clearPassword = () => {
		this.refs.passwordInput.clear();
		this.loginInfo.password = '';
		this.setState({
			passwordClearOpacity: 0
		})
	}

	togglePassword = () => {
		this.setState({
			hidePassword: !this.state.hidePassword
		})
	}

	async saveUserInfo (userInfo) {
		GLOBAL.TOKEN = userInfo.authToken;
		GLOBAL.LOGIN_NAME = userInfo.loginName;
		this._registerJPush();
		Promise.all([
			Dictionary.init(),
			Permission.init(),
			StorageHelper.multiSet([
				[STORAGE_CONSTANT.USER_INFO_KEY, userInfo],
				[STORAGE_CONSTANT.TOKEN, userInfo.authToken],
				[STORAGE_CONSTANT.LOGIN_ACCOUNT_KEY, this.loginInfo.loginName],
			])
		]).then(() => {
			ToastUtil.showSuccess('登录成功').then(async () => {
				GLOBAL.CURR_MODULE = '2.0';
				this.requesting = false;
				this.props.navigation.navigate('Layout');
			})
		})
	}

	// 登录
	async login () {
		if (this.requesting) return;
		if (!this.formValidate()) return
		setTimeout(() => {
			Keyboard.dismiss();
		}, 0)
		this.loginInfo.devCode = appInfo.getUniqueID();
		this.setState({
			status: 'loading'
		})
		this.requesting = true;
		let loginResult = await HTTP.POST(API_GENERATE(API.DO_LOGIN), this.loginInfo);
		if (loginResult) {
			this.paramsData = {
				username: this.loginInfo.loginName,
				password: this.loginInfo.password,
			};
			Keychain.setGenericPassword(this.paramsData.username, this.paramsData.password);

			if (loginResult.pwdReset === 1) {
				GLOBAL.pwdReset = true;
				this.requesting = false;
				this.props.navigation.navigate('SetPassWordPage', { resetPwdToken: loginResult.token, pwdReset: true });
			} else {
				let userInfo = loginResult;
				await this.saveUserInfo(userInfo);
			}
		} else {
			this.requesting = false;
		}
		this.setState({
			status: 'data'
		})
	}

	// 表单验证
	formValidate () {
		let { loginName, password } = this.loginInfo;
		if (!loginName) {
			ToastUtil.showWarning('请输入账号');
			return
		}
		if (!password) {
			ToastUtil.showWarning('请输入密码');
			return
		}
		return true
	}

	async _registerJPush () {
		let APP_HOT_VERSION = await StorageHelper.get(STORAGE_CONSTANT.APP_HOT_VERSION);
		//极光推送
		if (!appInfo.isEmulator()) {
			let registrationId = await StorageHelper.get(STORAGE_CONSTANT.REGISTRATION_ID);
			await HTTP.POST(API_GENERATE(API.PUSH_REGISTER_INFO), {
				appVersion: appInfo.getVersion(),
				deviceCode: appInfo.getUniqueID(),
				deviceType: Platform.OS.substring(0, 1),
				osVersion: appInfo.getSystemVersion(),
				phoneBrand: appInfo.getModel(),
				phoneModel: appInfo.getModel(),
				registrationId: registrationId,
				extVersionCode: APP_HOT_VERSION
			});
		}
	}

	authenticate = async () => {
		Keychain.getGenericPassword().then(credentials => {
			if (credentials && credentials.username && credentials.password) {
				TouchID.authenticate('指纹/人脸识别登录', {
					title: '通过识别键验证',
					imageColor: '#e00606',
					imageErrorColor: '#ff0000',
					sensorDescription: '请放入手指识别',
					sensorErrorDescription: '识别失败，请重试',
					unifiedErrors: true,
					fallbackLabel: '账号登录',
					cancelText: '取消',
					passcodeFallback: false,
				}).then(success => {
					this.loginInfo.loginName = credentials.username;
					this.loginInfo.password = credentials.password;
					GLOBAL.BIND_LOGIN_TYPE = 'BIOMETRY'
            		StorageHelper.set(STORAGE_CONSTANT.BIND_LOGIN_TYPE, GLOBAL.BIND_LOGIN_TYPE);
					this.login();
				}).catch(error => {
					console.warn(error)
					if (error.code === 'NOT_ENROLLED') {
						ToastUtil.showWarning('请去对应的手机中心去设置指纹验证');
					} else if (error.code === 'UNKNOWN_ERROR') {
						ToastUtil.showWarning('出现未知错误,请再次验证');
					} else {
						// ToastUtil.showWarning('识别异常' + error.code);
					}
				});

			} else {
				ToastUtil.showWarning('请输入密码登入');
			}
		})
	}

	goGesture = async () => {
		this.props.navigation.navigate('gestureLogin',{
			refreshData: () => this.refreshData()
		})
	}


	render () {
		const currVersion = appInfo.getVersion();
		let { loginName, password } = this.loginInfo;
		let { status, accountClearOpacity, passwordClearOpacity, hidePassword, accountFocus, passwordFocus, isBind,gesture } = this.state;
		return (
			<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
				<TouchableOpacity style={{ height: ScreenHeight }} activeOpacity={1} onPress={() => { Keyboard.dismiss() }}>
					<StatusBar
						backgroundColor={style.color.themeColor}
						barStyle="light-content"
					/>
					<View style={styles.loginTopView}>
						<Animated.Image source={logoIcon} style={{ height: this.imageHeight, width: this.imageHeight }} />
						<Animated.Text style={[styles.logoText, { opacity: this.textOpacity }]}>{currVersion}<Text>{this.state.current_env_title}</Text>
						</Animated.Text>
						{
							ENVIRONMENT[GLOBAL.CURR_ENV].switchEnable ?
								<View style={styles.switchButton}>
									<Text style={styles.switchEnv} onPress={() => { this.switchEnviromentSelect() }}>切换环境</Text>
								</View>
								: null
						}
					</View>
					{/* 切换环境弹层 */}
					{
						(GLOBAL.CURR_ENV === 'PROD' || GLOBAL.CURR_ENV === 'ZHDS') ?
							<HxActionSheet
								ref={o => this.SwitchActionSheet = o}
								title={<View><Text style={styles.actionTitle}>注意：切换环境后需要重新登陆</Text></View>}
								titleIOS={'注意：切换环境后需要重新登陆'}
								options={['取消', <Text style={styles.sheetTextColor}>切换中化化销</Text>, <Text style={styles.sheetTextColor}>切换中化电商</Text>]}
								optionsIOS={['取消', '中化化销', '中化电商']}
								onPress={(i) => {
									this.switchEnviroment(envStatusProd[i]);
								}}
								destructiveButtonIndex={9}
								styles={{
									titleBox: {
										height: 63 * scale,
										marginBottom: 1 * scale
									}
								}}
							/> :
							<HxActionSheet
								ref={o => this.SwitchActionSheet = o}
								title={<View><Text style={styles.actionTitle}>注意：切换环境后需要重新登陆</Text></View>}
								titleIOS={'注意：切换环境后需要重新登陆'}
								options={['取消', <Text style={styles.sheetTextColor}>切换开发环境</Text>, <Text style={styles.sheetTextColor}>切换UAT环境</Text>, <Text style={styles.sheetTextColor}>切换测试环境</Text>, <Text style={styles.sheetTextColor}>切换油销演示环境</Text>]}
								optionsIOS={['取消', '切换开发环境', '切换测试环境', '切换UAT环境', '切换油销演示环境']}
								onPress={(i) => {
									this.switchEnviroment(envStatus[i]);
								}}
								destructiveButtonIndex={9}
								styles={{
									titleBox: {
										height: 63 * scale,
										marginBottom: 1 * scale
									}
								}}
							/>
					}
					{
						Platform.OS == 'ios' ? null :
							(<Image source={inputsCellShadow} style={[styles.inputsCellShadow]} />)
					}
					{/* 登录表单 */}
					<Animated.View style={[styles.inputsCell, { top: this.inputWrapTop, height: this.inputWrapHeight }]}>
						{/* 账号 */}
						<Animated.View style={[styles.textInputCell, { marginTop: this.inputMarginTop }]}>
							<View style={styles.labelCell}>
								<Text style={styles.labelText}>账号</Text>
							</View>
							<View style={styles.inputCont}>
								<TextInput
									ref="accountInput"
									style={styles.inputMain}
									underlineColorAndroid='transparent'
									returnKeyType='next'
									placeholder={"请输入账号名"}
									placeholderTextColor="#BFBFBF"
									maxLength={30}
									blurOnSubmit={false}
									onBlur={() => {
										this.setState({ accountFocus: false })
									}}
									onFocus={() => {
										this.setState({ accountFocus: true })
									}}
									// defaultValue={loginName}
									value={loginName}
									onChangeText={(txt) => this.getAccount(txt)}
									onSubmitEditing={() => { this.refs.passwordInput.focus(); }}
								/>

								{accountFocus ? (<TouchableOpacity onPress={() => this.clearAccount()} activeOpacity={0.5} style={[styles.inputRightIconBox]}>
									<Image source={inputClear} style={[styles.inputRightIconStyle, { opacity: accountClearOpacity }]} />
								</TouchableOpacity>) : null}
							</View>
						</Animated.View>

						{/* 密码 */}
						<Animated.View style={[styles.textInputCell, { marginTop: this.inputMarginTop }]}>
							<View style={styles.labelCell}>
								<Text style={styles.labelText}>密码</Text>
								<TouchableOpacity activeOpacity={1} style={styles.securePwdEntry} onPress={() => this.togglePassword()} >
									<Image source={hidePassword ? showIcon : hideIcon} style={styles.securePwdEntry} />
								</TouchableOpacity>
							</View>
							<View style={styles.inputCont}>
								<TextInput
									secureTextEntry={hidePassword}
									ref="passwordInput"
									style={styles.inputMain}
									underlineColorAndroid='transparent'
									returnKeyType='done'
									placeholder={"请输入密码"}
									placeholderTextColor="#BFBFBF"
									maxLength={20}
									blurOnSubmit={false}
									onBlur={() => {
										this.setState({ passwordFocus: false })
									}}
									onFocus={() => {
										this.setState({ passwordFocus: true })
									}}
									value={this.props.navigation.state.params && this.props.navigation.state.params.logOut ? '' : password}
									onChangeText={(txt) => this.getPassword(txt)}
									onSubmitEditing={() => this.login()}
								/>
								{passwordFocus ? (<TouchableOpacity onPress={() => this.clearPassword()} activeOpacity={0.5} style={[styles.inputRightIconBox]}>
									<Image source={inputClear} style={[styles.inputRightIconStyle, { opacity: passwordClearOpacity }]} />
								</TouchableOpacity>) : null}
							</View>
						</Animated.View>

						{/* 登录按钮 */}
						{/* <View style={styles.findPwdCell}>
							<Text style={styles.findPwdText} onPress={() => this.props.navigation.navigate('PassWordPage')}>忘记密码</Text>
						</View> */}
						<TouchableOpacity style={[styles.loginBtn, { bottom: 103 * scale }]} onPress={() => this.login()}>
							<Text style={styles.loginBtnText}>登录</Text>
						</TouchableOpacity>
						<View style={styles.logBtnBox}>
						{isBind ? (
							<TouchableOpacity style={styles.logBtn} onPress={this.authenticate}>
								<Text style={styles.loginBtnTetie}>
									指纹/人脸登录
	              				</Text>
							</TouchableOpacity>
						 ) : null}
						{gesture?
							<TouchableOpacity style={styles.logBtn} onPress={this.goGesture}>
								<Text style={styles.loginBtnTetie}>
									手势登录
								</Text>
							</TouchableOpacity>
							:null}
						</View>
					</Animated.View>

				</TouchableOpacity>
				{
					status == 'loading' ? (<View style={{ position: 'absolute', height: ScreenHeight, width: ScreenWidth, top: 0 }}>
						<PageStatusIndex status={status} />
					</View>
					) : null
				}
			</KeyboardAvoidingView>
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#fff',
		alignItems: 'center',
	},
	loginTopView: {
		width: 375 * scale,
		height: 272 * scale,
		paddingTop: 54 * scale,
		alignItems: 'center',
		backgroundColor: style.color.themeColor,
		position: 'relative',
		overflow: 'visible'
	},
	// logoIcon: {
	// 	width: 70 * scale,
	// 	height: 70 * scale,
	// },
	logoText: {
		marginTop: 12 * scale,
		width: 375 * scale,
		height: 30 * scale,
		fontSize: 16 * scale,
		color: '#fff',
		textAlign: 'center'
	},
	switchButton: {
		borderBottomColor: '#fff',
		borderBottomWidth: 1 / PixelRatio.get(),
		position: 'absolute',
		top: 80 * scale,
		right: 25 * scale,
	},
	switchEnv: {
		color: '#fff',
		fontSize: 16 * scale,
	},
	inputsCellShadow: {
		position: 'absolute',
		width: 339 * scale,
		top: 180 * scale,
		left: 18 * scale,
	},
	inputsCell: {
		backgroundColor: '#fff',
		position: 'absolute',
		width: 335 * scale,
		height: 387 * scale,
		borderRadius: 8,
		left: 20 * scale,
		paddingTop: 10 * scale,
		alignItems: 'center',
		shadowColor: '#D2D2D2',
		shadowOffset: { width: 0, height: 6 * scale },
		shadowRadius: 2,
		shadowOpacity: 0.5,
	},
	textInputCell: {
		width: 279 * scale,
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
	},
	labelCell: {
		height: 18 * scale,
		flexDirection: 'row',
		alignItems: 'flex-end',
		justifyContent: 'space-between',
		marginBottom: 5 * scale,
	},
	labelText: {
		fontSize: 14 * scale,
		color: '#404040',
	},
	inputCont: {
		flexDirection: 'row',
		alignItems: 'flex-end',
		justifyContent: 'space-between',
	},
	inputMain: {
		borderWidth: 0,
		fontSize: 14 * scale,
		width: 256 * scale,
		height: 40 * scale,
	},
	inputRightIconBox: {
		height: 40 * scale,
		width: 30 * scale,
		alignItems: 'center',
		justifyContent: 'center',
	},
	inputRightIconStyle: {
		height: 14 * scale,
		width: 14 * scale,
		// marginRight: 5 * scale,
	},
	findPwdCell: {
		flex: 1,
		height: 17 * scale,
		paddingTop: 13 * scale,
		width: 279 * scale,
		alignItems: 'flex-end'
	},
	securePwdEntry: {
		width: 16 * scale,
		height: 16 * scale,
	},
	findPwdText: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
	},
	loginBtn: {
		width: 300 * scale,
		height: 44 * scale,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: style.color.themeColor,
		borderRadius: 82,
		position: 'absolute',
		left: 13 * scale,
		// bottom: 153 * scale,
	},
	logBtn: {
		// width: 150 * scale,
		height: 44 * scale,
		flex:1,
		alignItems:"center",
		justifyContent: 'center',
		// backgroundColor:'red'
		// justifyContent: 'center',
		// alignItems: 'center',
	},
	logBtnBox:{
		width:"100%",
		flexDirection:'row',
		justifyContent: 'center',
		alignItems: 'center',
		position:'absolute',
		// left: 13 * scale,
		bottom: 30 * scale,
	},
	loginBtnText: {
		fontSize: 14 * scale,
		color: '#fff',
	},
	loginBtnTetie: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
	},
})